package com.axzhengxin.platform.common.util;

import com.axzhengxin.platform.common.props.ElasticSearchProps;
import lombok.SneakyThrows;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * ElasticSearchUtil
 *
 * @author jiangnan
 * @date 2021/3/18
 */
@Component
public class ElasticSearchUtil {

    private static ElasticSearchProps props;

    @SneakyThrows
    public static TransportClient getClient() {
        Settings settings = Settings.settingsBuilder()
                .put("elasticsearch", props.getClusterName()).build();
        return TransportClient.builder().settings(settings).build().
                addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(props.getHost()), props.getPort()));
    }

    @Autowired
    public void setProps(ElasticSearchProps props) {
        ElasticSearchUtil.props = props;
    }

}
